import pandas as pd
from zc_core.client.mongo_client import Mongo


def export_attr(collection, columns, header, file):
    db = Mongo()

    src = db.list(collection)
    exp_list = list()
    for row in src:
        cat_id = row.get('_id')
        cat_name = row.get('catName')
        attrs = row.get('attrs', [])
        for attr in attrs:
            group = attr.get('group')
            props = attr.get('categoryAttributeWithProperties', [])
            for prop in props:
                kv = prop.get('categoryAttribute', {})
                required = kv.get('attrMetasForK', {}).get('REQUIRED', 'false')
                required = '必填' if required == 'true' else '选填'

                exp_row = dict()
                exp_row['catId'] = cat_id
                exp_row['catName'] = cat_name
                exp_row['group'] = group
                exp_row['propId'] = kv.get('propertyId')
                exp_row['propName'] = kv.get('attrKey', '')
                exp_row['propCode'] = kv.get('property', {}).get('code')
                exp_row['required'] = required
                vals = kv.get('attrVals', []) or []
                exp_row['propValues'] = '\n'.join(vals)
                exp_list.append(exp_row)
        print('cat: %s' % cat_id)

    pd.DataFrame(exp_list).to_excel(file, columns=columns, header=header, encoding='utf-8', index=False)


if __name__ == '__main__':
    # batch_no = time_to_batch_no(datetime.now())
    batch_no = '20211018'
    export_attr(
        'cat_attr_{}'.format(batch_no),
        ['catId', 'catName', 'group', 'propId', 'propCode', 'propName', 'required', 'propValues'],
        ['小类编号', '小类名称', '属性组', '属性编号', '英文编码', '属性名称', '是否必填', '可选值'],
        'D:\\国税规格参数_{}.xlsx'.format(batch_no)
    )
